export default class NetWork {
  constructor() {
    this.networkType = "none";
    this.isConnected = false;
    this.isFetching = false;
  }

  static getInstance() {
    this.instance = this.instance || new NetWork();
    return this.instance;
  }

  request() {
    this.isFetching = true;
  }

  requestOver() {
    this.isFetching = false;
  }

  init() {
    return new Promise((resolve, reject) => {
      wx.getNetworkType({
        success: (res) => {
          const networkType = res.networkType;
          this.networkType = networkType;
          this.isConnected = true;
          // wx.showToast({
          //   title: `当前网络${networkType}`,
          //   icon: "none",
          // })

          wx.onNetworkStatusChange((res) => {
            this.isConnected = res.isConnected;
            this.networkType = res.networkType;
            // wx.showToast({
            //   title: `是否有网络${res.isConnected},当前网络${res.networkType}`,
            //   icon: "none",
            // })
            if (!this.isConnected && this.isFetching) {
              wx.showToast({
                title: `网络已断开，检查网络后重试`,
                icon: "none",
                duration: 5000,
              });
            }

            if (this.isConnected) {
              this.isFetching = false;
            }
          });

          resolve();
        },
      });
    });
  }
}
